<!DOCTYPE html>
<html lang="zh-CN" data-theme="light">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>高级科学计算器</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/daisyui@3.9.4/dist/full.css" rel="stylesheet" type="text/css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        .calculator-btn {
            transition: all 0.2s ease;
            transform: scale(1);
            min-height: 3.5rem;
            font-size: 1.2rem;
            font-weight: 500;
        }
        .calculator-btn:active {
            transform: scale(0.95);
        }
        .display-text {
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        .history-item {
            transition: all 0.2s;
            cursor: pointer;
            padding: 0.3rem 0.5rem;
            border-radius: 0.3rem;
        }
        .history-item:hover {
            background-color: rgba(0,0,0,0.05);
        }
        .theme-btn {
            position: absolute;
            top: 20px;
            right: 20px;
            z-index: 10;
            width: 2.8rem;
            height: 2.8rem;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .display-container {
            background: rgba(255, 255, 255, 0.85);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(209, 213, 219, 0.5);
        }
        .number-btn {
            background: linear-gradient(to bottom, #ffffff, #f3f4f6);
            border: 1px solid #e5e7eb;
            color: #374151;
        }
        .number-btn:hover {
            background: linear-gradient(to bottom, #f9fafb, #e5e7eb);
        }
        .operator-btn {
            background: linear-gradient(to bottom, #3b82f6, #2563eb);
            color: white;
            border: 1px solid #3b82f6;
        }
        .operator-btn:hover {
            background: linear-gradient(to bottom, #2563eb, #1d4ed8);
        }
        .function-btn {
            background: linear-gradient(to bottom, #8b5cf6, #7c3aed);
            color: white;
            border: 1px solid #8b5cf6;
        }
        .function-btn:hover {
            background: linear-gradient(to bottom, #7c3aed, #6d28d9);
        }
        .equals-btn {
            background: linear-gradient(to bottom, #10b981, #059669);
            color: white;
            border: 1px solid #10b981;
            font-size: 1.3rem;
        }
        .equals-btn:hover {
            background: linear-gradient(to bottom, #059669, #047857);
        }
        .special-btn {
            background: linear-gradient(to bottom, #f59e0b, #d97706);
            color: white;
            border: 1px solid #f59e0b;
        }
        .special-btn:hover {
            background: linear-gradient(to bottom, #d97706, #b45309);
        }
        @media (max-width: 480px) {
            .calculator-btn {
                min-height: 2.8rem;
                font-size: 1.1rem;
            }
        }
    </style>
</head>
<body class="min-h-screen bg-gradient-to-br from-indigo-50 to-purple-100 flex items-center justify-center p-4">
    <button class="theme-btn btn btn-circle shadow-md bg-indigo-600 text-white" onclick="toggleTheme()">
        <i class="fas fa-moon"></i>
    </button>
    
    <div class="card w-full max-w-md bg-base-100 shadow-2xl border border-gray-200 rounded-2xl overflow-hidden">
        <div class="card-body p-5">
            <h2 class="card-title text-2xl font-bold text-indigo-700 mb-4 flex items-center justify-center">
                <i class="fas fa-calculator mr-2"></i>科学计算器
            </h2>
            
            <!-- 显示屏 -->
            <div class="display-container rounded-xl p-4 mb-4 shadow-inner">
                <div id="history" class="text-right text-xs text-gray-500 h-4 mb-1 opacity-80"></div>
                <div id="operation" class="text-right text-sm text-gray-600 h-6 mb-1 display-text"></div>
                <div id="display" class="text-right text-3xl font-semibold text-gray-800 h-10 display-text">0</div>
            </div>
            
            <!-- 函数按钮区 -->
            <div class="grid grid-cols-5 gap-2 mb-3">
                <button onclick="appendFunction('sin(')" class="calculator-btn function-btn">sin</button>
                <button onclick="appendFunction('cos(')" class="calculator-btn function-btn">cos</button>
                <button onclick="appendFunction('tan(')" class="calculator-btn function-btn">tan</button>
                <button onclick="appendFunction('log(')" class="calculator-btn function-btn">log</button>
                <button onclick="appendFunction('ln(')" class="calculator-btn function-btn">ln</button>
            </div>
            
            <!-- 基础运算按钮区 -->
            <div class="grid grid-cols-4 gap-3" id="basic-calculator">
                <!-- 第一行 -->
                <button onclick="clearAll()" class="calculator-btn special-btn">AC</button>
                <button onclick="backspace()" class="calculator-btn special-btn"><i class="fas fa-delete-left"></i></button>
                <button onclick="appendFunction('(')" class="calculator-btn function-btn">(</button>
                <button onclick="appendFunction(')')" class="calculator-btn function-btn">)</button>
                
                <!-- 第二行 -->
                <button onclick="appendFunction('π')" class="calculator-btn function-btn">π</button>
                <button onclick="appendFunction('e')" class="calculator-btn function-btn">e</button>
                <button onclick="appendFunction('^')" class="calculator-btn function-btn">x^y</button>
                <button onclick="appendFunction('sqrt(')" class="calculator-btn function-btn">√</button>
                
                <!-- 第三行 -->
                <button onclick="appendNumber('7')" class="calculator-btn number-btn">7</button>
                <button onclick="appendNumber('8')" class="calculator-btn number-btn">8</button>
                <button onclick="appendNumber('9')" class="calculator-btn number-btn">9</button>
                <button onclick="appendOperator('/')" class="calculator-btn operator-btn">÷</button>
                
                <!-- 第四行 -->
                <button onclick="appendNumber('4')" class="calculator-btn number-btn">4</button>
                <button onclick="appendNumber('5')" class="calculator-btn number-btn">5</button>
                <button onclick="appendNumber('6')" class="calculator-btn number-btn">6</button>
                <button onclick="appendOperator('*')" class="calculator-btn operator-btn">×</button>
                
                <!-- 第五行 -->
                <button onclick="appendNumber('1')" class="calculator-btn number-btn">1</button>
                <button onclick="appendNumber('2')" class="calculator-btn number-btn">2</button>
                <button onclick="appendNumber('3')" class="calculator-btn number-btn">3</button>
                <button onclick="appendOperator('-')" class="calculator-btn operator-btn">−</button>
                
                <!-- 第六行 -->
                <button onclick="toggleSign()" class="calculator-btn function-btn">±</button>
                <button onclick="appendNumber('0')" class="calculator-btn number-btn">0</button>
                <button onclick="appendNumber('.')" class="calculator-btn number-btn">.</button>
                <button onclick="appendOperator('+')" class="calculator-btn operator-btn">+</button>
                
                <!-- 第七行 -->
                <button onclick="handlePercentage()" class="calculator-btn function-btn col-span-2">%</button>
                <button onclick="appendFunction('fact(')" class="calculator-btn function-btn">n!</button>
                <button onclick="calculate()" class="calculator-btn equals-btn col-span-1">=</button>
            </div>
            
            <!-- 历史记录区域 -->
            <div class="mt-4 border-t border-gray-200 pt-3">
                <div class="text-sm font-semibold text-gray-600 mb-2 flex justify-between">
                    <span><i class="fas fa-history mr-1"></i>计算历史</span>
                    <button onclick="clearHistory()" class="text-xs btn btn-xs btn-ghost">清空</button>
                </div>
                <div id="history-list" class="max-h-32 overflow-y-auto text-sm space-y-1 pr-2">
                    <!-- 历史记录将在这里动态生成 -->
                </div>
            </div>
        </div>
    </div>

    <script>
        let currentInput = '0';
        let fullExpression = '';
        let resetInput = false;
        let calculationHistory = [];

        const display = document.getElementById('display');
        const operationDisplay = document.getElementById('operation');
        const historyList = document.getElementById('history-list');
        const historyDisplay = document.getElementById('history');

        // 初始化显示
        updateDisplay();
        
        function updateDisplay() {
            display.textContent = currentInput;
            operationDisplay.textContent = fullExpression;
        }
        
        function appendNumber(number) {
            // 处理错误状态
            if (currentInput === 'Error') {
                clearAll();
            }
            
            // 处理小数点
            if (number === '.') {
                if (currentInput.includes('.')) {
                    return; // 防止输入多个小数点
                }
                if (resetInput || currentInput === '0') {
                    currentInput = '0.';
                    resetInput = false;
                    fullExpression += '0.';
                    updateDisplay();
                    return;
                }
            }
            
            if (currentInput === '0' || resetInput) {
                currentInput = number;
                resetInput = false;
            } else {
                currentInput += number;
            }
            
            // 如果当前输入是函数的一部分，则追加到完整表达式
            if (fullExpression.endsWith(')') || /[+\-*/^]/.test(fullExpression.slice(-1))) {
                fullExpression += currentInput;
            } else {
                fullExpression = fullExpression.slice(0, -currentInput.length + 1) + currentInput;
            }
            
            updateDisplay();
        }

        function appendOperator(op) {
            // 处理错误状态
            if (currentInput === 'Error') {
                clearAll();
            }
            
            // 避免连续输入运算符
            const lastChar = fullExpression.slice(-1);
            if (['+', '-', '*', '/', '^'].includes(lastChar)) {
                fullExpression = fullExpression.slice(0, -1) + op;
            } else {
                fullExpression += op;
            }
            
            currentInput = op;
            resetInput = true;
            updateDisplay();
        }

        function appendFunction(func) {
            // 处理错误状态
            if (currentInput === 'Error') {
                clearAll();
            }
            
            // 特殊常数处理
            if (func === 'π') {
                if (resetInput || currentInput === '0') {
                    currentInput = 'π';
                    fullExpression += 'Math.PI';
                } else {
                    currentInput += 'π';
                    fullExpression += '*Math.PI';
                }
                resetInput = false;
                updateDisplay();
                return;
            }
            
            if (func === 'e') {
                if (resetInput || currentInput === '0') {
                    currentInput = 'e';
                    fullExpression += 'Math.E';
                } else {
                    currentInput += 'e';
                    fullExpression += '*Math.E';
                }
                resetInput = false;
                updateDisplay();
                return;
            }
            
            // 幂运算处理
            if (func === '^') {
                fullExpression += '**';
                currentInput = '^';
                resetInput = true;
                updateDisplay();
                return;
            }
            
            // 其他函数处理
            fullExpression += func;
            
            if (func.endsWith('(')) {
                currentInput = func;
                resetInput = true;
            } else {
                currentInput = func;
            }
            
            updateDisplay();
        }
        
        function handlePercentage() {
            if (currentInput === '0' || currentInput === 'Error') return;
            
            try {
                const value = parseFloat(currentInput);
                const percentage = value / 100;
                currentInput = percentage.toString();
                
                // 更新完整表达式
                const exprParts = fullExpression.split(/([+\-*/^])/);
                if (exprParts.length > 0) {
                    exprParts[exprParts.length - 1] = percentage.toString();
                    fullExpression = exprParts.join('');
                }
                
                updateDisplay();
            } catch (e) {
                currentInput = 'Error';
                updateDisplay();
            }
        }

        function calculate() {
            try {
                if (fullExpression.trim() === '') return;
                
                // 替换显示符号为JS可识别的
                let expr = fullExpression
                    .replace(/×/g, '*')
                    .replace(/÷/g, '/')
                    .replace(/\^/g, '**')
                    .replace(/π/g, 'Math.PI')
                    .replace(/e/g, 'Math.E')
                    .replace(/sqrt\(/g, 'Math.sqrt(')
                    .replace(/sin\(/g, 'Math.sin(')
                    .replace(/cos\(/g, 'Math.cos(')
                    .replace(/tan\(/g, 'Math.tan(')
                    .replace(/log\(/g, 'Math.log10(')
                    .replace(/ln\(/g, 'Math.log(')
                    .replace(/fact\(/g, 'factorial(')
                    .replace(/pow\(/g, 'Math.pow(');
                
                // 添加缺少的右括号
                const openParens = (expr.match(/\(/g) || []).length;
                const closeParens = (expr.match(/\)/g) || []).length;
                for (let i = 0; i < openParens - closeParens; i++) {
                    expr += ')';
                }
                
                // 阶乘函数实现
                function factorial(n) {
                    if (n < 0) return NaN;
                    if (n === 0 || n === 1) return 1;
                    let result = 1;
                    for (let i = 2; i <= n; i++) {
                        result *= i;
                    }
                    return result;
                }
                
                // 计算表达式
                const result = eval(expr);
                
                // 保存历史记录
                calculationHistory.push({
                    expression: fullExpression,
                    result: result
                });
                updateHistory();
                
                // 更新显示
                currentInput = formatResult(result);
                fullExpression = currentInput;
                resetInput = true;
                historyDisplay.textContent = '= ' + currentInput;
                updateDisplay();
            } catch (e) {
                currentInput = 'Error';
                updateDisplay();
            }
        }
        
        function formatResult(value) {
            // 处理大数字和小数
            if (typeof value === 'number') {
                if (Math.abs(value) > 1e12 || (Math.abs(value) < 1e-6 && value !== 0)) {
                    return value.toExponential(6).replace(/(\.\d*?[1-9])0+e/, '$1e');
                }
                
                // 处理浮点数精度问题
                const strValue = value.toString();
                if (strValue.includes('.') && strValue.length > 12) {
                    return value.toFixed(10).replace(/\.?0+$/, '');
                }
                
                // 处理整数
                if (Number.isInteger(value)) {
                    return value.toString();
                }
            }
            return value.toString();
        }
        
        function updateHistory() {
            historyList.innerHTML = '';
            const reversedHistory = [...calculationHistory].reverse().slice(0, 5);
            
            reversedHistory.forEach(item => {
                const historyItem = document.createElement('div');
                historyItem.className = 'history-item flex justify-between';
                historyItem.innerHTML = `
                    <div class="text-gray-600 truncate max-w-[70%]">${item.expression}</div>
                    <div class="font-medium text-indigo-700">= ${formatResult(item.result)}</div>
                `;
                
                historyItem.addEventListener('click', () => {
                    fullExpression = item.expression;
                    currentInput = item.result.toString();
                    resetInput = true;
                    historyDisplay.textContent = '';
                    updateDisplay();
                });
                
                historyList.appendChild(historyItem);
            });
        }
        
        function clearAll() {
            currentInput = '0';
            fullExpression = '';
            resetInput = false;
            historyDisplay.textContent = '';
            updateDisplay();
        }
        
        function clearHistory() {
            calculationHistory = [];
            historyList.innerHTML = '';
        }
        
        function backspace() {
            if (currentInput === 'Error') {
                clearAll();
                return;
            }
            
            if (currentInput.length > 1) {
                currentInput = currentInput.slice(0, -1);
                fullExpression = fullExpression.slice(0, -1);
            } else {
                currentInput = '0';
                fullExpression = fullExpression.slice(0, -1);
            }
            
            // 如果表达式为空，重置为0
            if (fullExpression === '') {
                currentInput = '0';
            }
            
            updateDisplay();
        }

        function toggleSign() {
            if (currentInput === '0' || currentInput === 'Error') return;
            
            if (currentInput.startsWith('-')) {
                currentInput = currentInput.slice(1);
                fullExpression = fullExpression.replace(/-\s*([\d.]+)$/, '$1');
            } else {
                currentInput = '-' + currentInput;
                
                // 检查表达式最后一部分是否是数字
                const exprParts = fullExpression.split(/([+\-*/^])/);
                if (exprParts.length > 0) {
                    const lastPart = exprParts[exprParts.length - 1];
                    if (!isNaN(lastPart)) {
                        exprParts[exprParts.length - 1] = `-${lastPart}`;
                        fullExpression = exprParts.join('');
                    }
                }
            }
            
            updateDisplay();
        }
        
        function toggleTheme() {
            const themeBtn = document.querySelector('.theme-btn');
            const currentTheme = document.documentElement.getAttribute('data-theme');
            
            if (currentTheme === 'light') {
                document.documentElement.setAttribute('data-theme', 'dark');
                themeBtn.innerHTML = '<i class="fas fa-sun"></i>';
                themeBtn.classList.remove('bg-indigo-600');
                themeBtn.classList.add('bg-yellow-500');
                document.body.classList.remove('from-indigo-50', 'to-purple-100');
                document.body.classList.add('from-gray-800', 'to-gray-900');
            } else {
                document.documentElement.setAttribute('data-theme', 'light');
                themeBtn.innerHTML = '<i class="fas fa-moon"></i>';
                themeBtn.classList.remove('bg-yellow-500');
                themeBtn.classList.add('bg-indigo-600');
                document.body.classList.remove('from-gray-800', 'to-gray-900');
                document.body.classList.add('from-indigo-50', 'to-purple-100');
            }
        }
    </script>
</body>
</html>